package cinema.Controller;

import cinema.Dao.ReservationDAO;
import cinema.Dao.SeatDAO;
import cinema.Dao.TimeTableDAO;
import cinema.Entity.Reservation;
import cinema.Entity.Seat;
import cinema.Entity.TimeTable;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

@ManagedBean(name = "reservationController")
@ViewScoped
public class ReservationController implements Serializable {

    private static TimeTable timeTable;
    @Inject
    TimeTableDAO timeTableDAO;
    @Inject
    ReservationDAO reservationDAO;
    @Inject
    SeatDAO seatDAO;
    @ManagedProperty(value = "#{seatBean}")
    private ChooseSeatController seatBean;
    private String name, email, phone, address;
    private List<Map.Entry<Integer, Integer>> seatList;

    @PostConstruct
    public void init() {
        this.seatList = seatBean.getSeatList();
    }

    public String process() {
        FacesContext fc = FacesContext.getCurrentInstance();
        Map<String, String> params = fc.getExternalContext().getRequestParameterMap();

        timeTable = timeTableDAO.findById(Integer.parseInt(params.get("timeTableID")));

        return "orderInfo?faces-redirect=true";
    }

    public String complete() {
        for (Map.Entry entry : seatList) {
            int row = (Integer) entry.getKey();
            int seatNumber = (Integer) entry.getValue();

            Reservation reservation = new Reservation(email, timeTable);
            reservationDAO.save(reservation);

            Seat seat = new Seat(reservation, row, seatNumber);
            seatDAO.save(seat);
        }

        return "reservationComplete?faces-redirect=true";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public ChooseSeatController getSeatBean() {
        return seatBean;
    }

    public void setSeatBean(ChooseSeatController seatBean) {
        this.seatBean = seatBean;
    }
}